import React, { lazy, Suspense, useEffect } from 'react';
import {
  useRoutes,
  RouteObject,
  Navigate,
  useNavigate
} from 'react-router-dom';

// 类型声明
namespace SyncRoute {
  export type Route = {
    path: string;
    component: React.LazyExoticComponent<any>;
    children?: Route[];
  };
}

// 初始化定义路由
const RouteTable: SyncRoute.Route[] = [
  {
    path: '/',
    component: lazy(() => import('@/views/layout')),
    children: []
  },
  {
    path: '/login',
    component: lazy(() => import('@/views/login')),
    children: []
  }
];

const syncRouter = (table: SyncRoute.Route[]) => {
  let mRouteTable: RouteObject[] = [];
  table.forEach((res) => {
    mRouteTable.push({
      path: res.path,
      element: (
        <Suspense fallback="加载中....">
          <res.component></res.component>
        </Suspense>
      ),
      children: res.children && syncRouter(res.children)
    });
  });
  return mRouteTable;
};

// 初始化跳转login界面
function RouterComponent() {
  const navigate = useNavigate();
  useEffect(() => {
    if (!localStorage.getItem('token')) {
      navigate('/login');
    }
  }, [navigate]);
  return useRoutes(syncRouter(RouteTable));
}
export default RouterComponent;
